package com.example.demo.heima.netty.client;

import com.example.demo.heima.netty.UserInfo;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname NettyClientHandler
 * @description
 * @date 2023/07/21 22:50
 * <p>
 * ******************************************************
 */
public class NettyClientInBoundHandler1 extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("NettyClientHandler channelActive");

        // 向服务端写数据
        /*Channel channel = ctx.channel();
        ByteBuf buffer = channel.alloc().buffer();
        buffer.writeBytes("hello nioserver".getBytes(StandardCharsets.UTF_8));
        channel.writeAndFlush(buffer);*/

        //批量发送数据
        UserInfo userInfo;
        for (int i=0;i<100;i++) {
            userInfo = new UserInfo(i,"name"+i,i+1,(i%2==0) ? "男":"女","北京");
            ctx.writeAndFlush(ctx.alloc().buffer().writeBytes(userInfo.toString().getBytes(StandardCharsets.UTF_8)));
        }

        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("NettyClientHandler channelInactive");
        super.channelInactive(ctx);
    }

    /**
     * 有数据时回调
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("NettyClientHandler channelRead");

        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);

        String content = new String(bytes, Charset.defaultCharset());
        System.out.println("收到的数据：" + content);
        super.channelRead(ctx, msg);
    }

    /**
     * bytebuf读完数据的回调
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("NettyClientHandler channelReadComplete");

        // 向服务器写回数据，千万别写回，不然你就知道什么叫死循环
//        Channel channel = ctx.channel();
//        ByteBuf buffer = channel.alloc().buffer();
//        buffer.writeBytes("hello nioserver".getBytes(StandardCharsets.UTF_8));
//        channel.writeAndFlush(buffer);
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("NettyClientHandler exceptionCaught" + cause.getMessage());
        super.exceptionCaught(ctx, cause);
    }
}
